<template>
  <el-button type="primary" class="add-student-btn" @click="addStudent">
    添加学生
  </el-button>
  <el-table :data="filteredStudents" style="width: 100%" :fit="true">
    <el-table-column label="编号" prop="id" width="80" align="center" show-overflow-tooltip />
    <el-table-column label="姓名" prop="name" width="120" align="center" show-overflow-tooltip />
    <el-table-column label="性别" prop="gender" width="80" align="center" show-overflow-tooltip />
    <el-table-column label="年龄" prop="age" width="80" align="center" show-overflow-tooltip />
    <el-table-column label="手机" prop="cellphone" width="140" align="center" show-overflow-tooltip />
    <el-table-column label="籍贯" prop="address" width="200" align="center" show-overflow-tooltip />

    <!-- 右侧操作列 -->
    <el-table-column label="操作" align="center">
      <template #header>
        <el-input
            v-model="keyword"
            size="default"
            placeholder="搜索学生"
            clearable
            style="width: 180px;"
        />
      </template>
      <template #default="scope">
        <el-button size="small" type="primary" @click="editStudent(scope.row)">
          编辑
        </el-button>
        <el-button size="small" type="danger" @click="deleteStudent(scope.row.id)">
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--  <el-pagination background layout="prev, pager, next" :total="1000" />-->
  <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize" @current-change="loadStudent"/>
  <!-- 编辑学生对话框 -->
  <el-dialog title="编辑学生" v-model="dialogFormVisible" width="500px">
    <el-form :model="student" ref="studentForm" label-width="80px">
      <el-form-item label="姓名">
        <el-input v-model="student.name" />
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="student.gender">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>
      <el-form-item label="年龄">
        <el-input v-model="student.age" type="number" />
      </el-form-item>
      <el-form-item label="手机">
        <el-input v-model="student.cellphone" />
      </el-form-item>
      <el-form-item label="籍贯">
        <el-input v-model="student.address" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogFormVisible = false">取消</el-button>
      <el-button type="primary" @click="saveStudent">保存</el-button>
    </template>
  </el-dialog>
</template>

<script>
export default {
  name: "StudentView",
  data() {
    return {
      students: [],
      keyword: "",
      current: 1, //当前页
      pageSize: 10, //页大小
      total: 10,   //总数
      dialogFormVisible: false,  //对话框是否显示
      student: {} //当前学生
    };
  },
  computed: {
    filteredStudents() {
      return this.students.filter(student =>
          student.name.includes(this.keyword) ||
          student.cellphone.includes(this.keyword)
      );
    }
  },
  methods: {
    loadStudents() {
      this.$axios.get("/findStudents").then(result => {
        if (result.data.code === 200) {
          this.students = result.data.data;
        }
      });

    },

    //编辑学生
    editStudent(stu){
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.studentForm && this.$refs.studentForm.clearValidate();
      });

      //学生回显效果  stu --> string ---> 对象 深克隆
      this.student = JSON.parse(JSON.stringify(stu));
    },
    /*  saveStudent() {
        this.$axios.post("/updatestudent", this.student).then(result => {
          if (result.data.code === 200) {
            this.$message.success("编辑成功");
            this.dialogFormVisible = false;
            this.loadStudent(this.current); // 重新加载数据
          } else {
            this.$message.error("编辑失败，请稍后重试");
          }
        });
      },*/
    /*    saveStudent() {
          this.$axios.post("/updatestudent", this.student).then(result => {
            if (result.data.code === 200) {
              this.$message.success("编辑成功");
              this.dialogFormVisible = false;
              this.loadStudent(this.current); // 重新加载数据
            } else {
              this.$message.error("编辑失败，请稍后重试");
            }
          }).catch(error => {
            this.$message.error("请求失败: " + error.message);
          });
        },*/


    deleteStudent(id) {
      this.$confirm("确定删除该学生吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$axios
            .post("/removestudent", { id }) // 发送删除请求到后端
            .then(result => {
              if (result.data.code === 200) {
                this.students = this.students.filter(student => student.id !== id);
                this.$message.success("删除成功");
              } else {
                this.$message.error("删除失败，请稍后重试");
              }
            })
            .catch(() => {
              this.$message.error("请求失败，请检查网络");
            });
      }).catch(() => {
        this.$message.info("已取消删除");
      });
    },


    loadStudent(current){
      this.current = current
      this.$axios.get('/findStudentPage?current=' + this.current + "&pageSize=" + this.pageSize)
          .then(result => {
            console.log('student',result.data)
            if(result.data.code === 200){
              this.students = result.data.data.data;
              this.total = result.data.data.total;
            }
          })
    },
    addStudent() {
      this.student = {}; // 清空表单，确保是新增
      this.dialogFormVisible = true;
    },
    saveStudent() {
      if (this.student.id) {
        // 调用更新学生的 API
        this.$axios.post("/updatestudent", this.student).then(result => {
          if (result.data.code === 200) {
            this.$message.success("编辑成功");
            this.dialogFormVisible = false;
            this.loadStudent(this.current); // 重新加载数据
          } else {
            this.$message.error("编辑失败，请稍后重试");
          }
        }).catch(error => {
          this.$message.error("请求失败: " + error.message);
        });
      } else {
        // 调用添加学生的 API
        this.$axios.post('/insertStudent', this.$qs.stringify(this.student))
            .then(result => {
              console.log('save', result.data);
              if (result.data.code === 200) {
                this.$message.success("添加成功");
                this.dialogFormVisible = false;
                this.loadStudent(1); // 重新加载第一页数据
              } else {
                this.$message.error("添加失败，请稍后重试");
              }
            }).catch(error => {
          this.$message.error("请求失败: " + error.message);
        });
      }
    }

  },
  mounted() {
    this.loadStudents();
    this.loadStudent(1)
  }
};


</script>

<style scoped>
.el-table {
  margin-top: 10px;
  border-radius: 8px;
}
.el-button {
  margin-right: 5px;
}
</style>
